package de.pellepelster.hudson.trafficlights;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.Logger;

/**
 * This Java based daemon aggregates the status of one ore more jobs from a hudson continous
 * integration server into a single status (red, yellow, green) and invokes a shell script on status
 * change.
 * 
 * @author Christian Pelster
 * @version $Rev$, $Date$
 */
public class HudsonTrafficLights {

	private static final String CONFIG_FILE_ARGUMENT = "c";
	private static final String CONFIG_FILE_DEFAULT_LOCATION = "/etc/hudson_traffic_lights.conf";
	private static final int HUDSON_POLLING_INTERVAL_DEFAULT = 5;
	private static final String HUDSON_POLLING_INTERVAL_ELEMENT_NAME = "pollingInterval";
	private static final String HUDSON_POLLING_JOBS_ELEMENT_NAME = "jobs.job";
	private static final String HUDSON_URL_CONFIG_ELEMENT_DEFAULT = "http://localhost:8080/hudson";
	private static final String HUDSON_URL_CONFIG_ELEMENT_NAME = "hudsonUrl";
	private static Logger log = Logger.getLogger(HudsonTrafficLights.class);
	private static final String WRAPPER_SCRIPT_CONFIG_ELEMENT_DEFAULT = "/usr/share/hudsontrafficlights/bin/traffic_lights_wrapper.sh";
	private static final String WRAPPER_SCRIPT_CONFIG_ELEMENT_NAME = "wrapperScript";
	private static final String WRAPPER_SCRIPT_TIMEOUT_CONFIG_ELEMENT_NAME = "wrapperScriptTimeout";
	private static final int WRAPPER_SCRIPT_TIMEOUT_CONFIG_DEFAULT = 1000;

	/**
	 * @param args
	 */
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {

		Options options = new Options();
		options.addOption(CONFIG_FILE_ARGUMENT, "config-file", true, String.format(
				"location of configuration file, default is '%s'", CONFIG_FILE_DEFAULT_LOCATION));

		CommandLineParser parser = new PosixParser();
		CommandLine cmd = null;
		try {
			cmd = parser.parse(options, args);
		}
		catch (ParseException e) {
			log.error("error parsing command line arguments", e);
			System.exit(1);
		}

		// load configuration file
		String configFileName = cmd
				.getOptionValue(CONFIG_FILE_ARGUMENT, CONFIG_FILE_DEFAULT_LOCATION);
		File configFile = new File(configFileName);
		if (configFile.exists()) {
			log.info(String.format("using config file '%s'", configFileName));
		}
		else {
			log.info(String.format("config file '%s' does not exist", configFileName));
		}

		XMLConfiguration config = null;
		try {
			config = new XMLConfiguration(configFile);
		}
		catch (ConfigurationException e) {
			log.info(String.format("error reading loading config file '%s'", configFileName));
		}

		String hudsonUrl = config.getString(HUDSON_URL_CONFIG_ELEMENT_NAME,
				HUDSON_URL_CONFIG_ELEMENT_DEFAULT);
		String wrapperScript = config.getString(WRAPPER_SCRIPT_CONFIG_ELEMENT_NAME,
				WRAPPER_SCRIPT_CONFIG_ELEMENT_DEFAULT);
		int wrapperScriptTimeout = config.getInt(WRAPPER_SCRIPT_TIMEOUT_CONFIG_ELEMENT_NAME,
				WRAPPER_SCRIPT_TIMEOUT_CONFIG_DEFAULT);
		int pollingInterval = config.getInt(HUDSON_POLLING_INTERVAL_ELEMENT_NAME,
				HUDSON_POLLING_INTERVAL_DEFAULT);
		List<String> jobs = config.getList(HUDSON_POLLING_JOBS_ELEMENT_NAME, new ArrayList<String>());

		String logMessage = String.format("starting polling hudson url '%s' every %d seconds for ",
				hudsonUrl, pollingInterval);

		if (jobs.isEmpty()) {
			logMessage += String.format("jobs %s", jobs.toString());
		}
		else {
			logMessage += "all jobs";
		}
		log.info(logMessage);

		HudsonTrafficLightsWorker worker = new HudsonTrafficLightsWorker(hudsonUrl, pollingInterval,
				jobs, wrapperScript, wrapperScriptTimeout);
		worker.run();
		log.info(String.format("finished polling"));

	}

}
